package com.study.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰和下划线互转工具类
 * @author hw
 * @date 2022/2/10 16:04:51
 */
public class HumpUnderlineUtil {

    /**
     * 驼峰转下划线
     * @author hw
     * @date 2022/2/10 16:05:23
     * @param str:目标字符串
     * @return java.lang.String
     */
    public static String humpToUnderline(String str) {
        String regex = "([A-Z])";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group();
            str = str.replaceAll(target, "_"+target.toLowerCase());
        }
        return str;
    }

    /**
     * 下划线转驼峰
     * @author hw
     * @date 2022/2/10 16:05:43
     * @param str:目标字符串
     * @return java.lang.String
     */
    public static String underlineToHump(String str) {
        str = str.toLowerCase();
        String regex = "_(.)";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group(1);
            str = str.replaceAll("_"+target, target.toUpperCase());
        }
        return str;
    }

}
